 #include <stdio.h>
 #include <errno.h>
 #include <string.h>
 #include <unistd.h>
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 #include <ctype.h>
 
 #define TMP_FILE        "/tmp/.ifconfig.log"
 
 int main(int argc,char *argv[])
 {       
         pid_t           pid;
         int             fd;
         char            buf[1024];
         int             rv;
         
         char            *ptr;
         FILE            *fp;
         char            *ip_start;
         char            *ip_end;
         char            ip_addr[16];
         
         
         if( (fd=open(TMP_FILE,O_RDWR|O_CREAT|O_TRUNC,0644)) < 0 )
         {
                 printf("Redirect standard output to file failure: %s\n",strerror(errno));
                 return -1;
         }
         printf("Redirect standard output file create successful\n");
 
         pid=fork();
         if(pid < 0)
         {
                 printf("Create child process failure: %s\n",strerror(errno));
                 return -2;
         }
         else if(pid == 0)
         {
                 printf("Child process create successful,start execute ifconfig program\n");
          
                 dup2(fd,STDOUT_FILENO);
                 execl("/sbin/ifconfig","ifconfig","wlan0",NULL);
                 printf("Child process execute another program,will not return here.Return here means execl() error\n");
                 return -3;
         
         
         }
 
         else
         {
                 sleep(3);
         }
 
         memset(buf,0,sizeof(buf));
         fp = fdopen(fd,"r");//文件描述符转变成文件指针
         fseek(fp,0,SEEK_SET);
         while(fgets(buf,sizeof(buf),fp))
         {
                 if( strstr(buf,"netmask") )
                 {
                 	ptr=strstr(buf,"inet");
		        if(!ptr)
			{
				break;
			}	
			ptr+=strlen("inet");
			while( isblank(*ptr) )
				ptr++;
			ip_start = ptr;

			while( !isblank(*ptr) )
				ptr++;
			ip_end = ptr;
			memset(ip_addr,0,sizeof(ip_addr));
			memcpy(ip_addr,ip_start,ip_end-ip_start);
			break;
                 }
		 printf("%s\n",buf);

         }

	 printf("Get IP address: %s\n",ip_addr);
	 fclose(fp);
	 unlink(TMP_FILE);

	 return 0;
 
 
 }

